#include <vector>
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

//定义锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ticket = 100;
void* ThreadRun(void* rags)
{
    char* name = (char*)rags;
    while(true)
    {
        //加锁
        pthread_mutex_lock(&mutex); 

        if(ticket>0){
            std::cout<<  name << " ticket: " << ticket << std::endl;
            --ticket;
            usleep(1000);

            //解锁
            pthread_mutex_unlock(&mutex); 
        }else{

            //解锁
            pthread_mutex_unlock(&mutex); 
            break;
        }
    }
    return nullptr;
}
int main()
{
    std::vector<pthread_t> tids;
    std::vector<char*> free;
    for(int i=0; i<5; ++i)
    {
        pthread_t id;
        char* name = new char[50];
        snprintf(name, 20, "thread-%d", i+1);
        free.push_back(name);

        pthread_create(&id, nullptr, ThreadRun, (void*)name);
        tids.push_back(id);
    }
    for(int i=0; i<5; ++i)
    {
        pthread_join(tids[i], nullptr);
        delete[] free[i];
    }
    return 0;
}


/*int ticket = 100;
void* ThreadRun(void* rags)
{
    while(true)
    {

        if(ticket>0){
            std::cout<< "ticket: " << ticket << std::endl;
            --ticket;
            usleep(1000);
        }else{
            break;
        }
    }
    return nullptr;
}
int main()
{
    std::vector<pthread_t> tids;
    for(int i=0; i<5; ++i)
    {
        pthread_t id;
        pthread_create(&id, nullptr, ThreadRun, nullptr);
        tids.push_back(id);
    }
    for(auto id:tids)
    {
        pthread_join(id, nullptr);
    }
    return 0;
}*/
